#coding:utf8
from rest_framework import serializers
from .models import OAuthQQUser
from django_redis import get_redis_connection
from users.models import User
from django.conf import settings



#ModelSerializer  --优势并不明显
# Serializer

class QQOauthCreateSerialzier(serializers.Serializer):

    access_token = serializers.CharField(label='操作token')
    # 正则匹配
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)



    def validate(self, attrs):

        # 验证用户提交的 access_token (openid)

        openid = OAuthQQUser.check_openid(attrs.get('access_token'))

        if openid is None:
            raise serializers.ValidationError('数据错误')

        #将openid放如 atts中 以便 validated_data 使用
        attrs['openid'] = openid


        # 验证短信码
        mobile = attrs['mobile']
        redis_conn = get_redis_connection('code')

        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code.decode() != attrs['sms_code']:
            raise serializers.ValidationError('验证码错误')


        # 根据手机号判断 是否存在注册用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            # 没有注册用户
            pass
        else:
            #有注册用户,我们校验密码
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码输入错误')
            attrs['user'] = user
            #xxxxxx

        return attrs


    def create(self, validated_data):

        user = validated_data.get('user')

        if user is None:
            #不存在 新建
            user = User.objects.create(
                mobile = validated_data.get('mobile'),
                password = validated_data.get('password'),
                username = validated_data.get('username')
            )

            user.set_password(validated_data.get('password'))
            user.save()


        # 给 绑定用户的模型进行数据入库
        OAuthQQUser.objects.create(
            openid=validated_data.get('openid'),
            user=user
        )


        return user

